'''
Created on 2011-2-12

@author: wilbur.ma
'''

import os
from ftplib import FTP
from pwilib.util.plugin.schema.NetTransport import NetTransport

class PythonFtp(NetTransport):
    '''
    A simple FTP client plugin.
    '''
    def __init__(self):
        NetTransport.__init__(self)
        self.transportBlockSize = 1024
        
        
    def connect(self, host=None, userName='', userPass='', workDir=None, port=21):
        if self.client is not None:
            self.client.quit()
        self.client = FTP()
        if host is None:
            print('No host defined, exit.')
            return
        self.client.connect(host, port)
        self.client.login(userName, userPass)
        if workDir is not None:
            self.client.cwd(workDir)
        
    def upload(self, filepath = None):
        if filepath is None:
            print('Nothing upload, exit.')
            return
        if self.client is None:
            print('Client not connected, exit.')
            return
        self.client.storbinary('STOR ' + os.path.basename(os.path.normcase(filepath)), open(filepath, 'rb'), self.transportBlockSize)
    
    def download(self, filename = None):
        if filename is None:
            print('Nothing upload, exit.')
            return
        if self.client is None:
            print('Client not connected, exit.')
            return
        self.client.retrbinary('RETR ' + filename)